package com.smiier.skin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.IntentCompat;
import android.text.Html;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OAlert;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.share.ShareWXUtils;
import com.igexin.sdk.PushManager;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuth.AuthInfo;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.UserSetTask;
import com.smiier.skin.net.UserSetTask.UserSetRequest;
import com.smiier.skin.net.UserSetTask.UserSetResponse;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.Util;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

public class LoginActivity extends BasicActivity {

	private EditText edit_username, edit_password;

	// private int login_type = GlobalSettings.LOGIN_TYPE_USERNAME;

	// 用于微信登陆，因为微信登陆需要通过中间Activity作回调，这是一种标记无语的实现方式
	public static String code;

	protected TextView mBottomText;
	SsoHandler mSsoHandler = null;

	private TextView close;
	private int mUserType;

	QQAuth mQQAuth = null;
	UserInfo mInfo = null;
	Tencent mTencent = null;

	String access_token = null;
	String weixin_Oppenid = null;

	protected static final String API_SERVER = "https://api.weibo.com/2";

	private static final int READ_USER = 0;
	private static final int READ_USER_BY_DOMAIN = 1;
	private static final int READ_USER_COUNT = 2;

	private static final String API_BASE_URL = API_SERVER + "/users";

	private static final SparseArray<String> sAPIList = new SparseArray<String>();
	static {
		sAPIList.put(READ_USER, API_BASE_URL + "/show.json");
		sAPIList.put(READ_USER_BY_DOMAIN, API_BASE_URL + "/domain_show.json");
		sAPIList.put(READ_USER_COUNT, API_BASE_URL + "/counts.json");
	}

	private File cache;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		edit_username = (EditText) findViewById(R.id.edit_username);
		edit_password = (EditText) findViewById(R.id.edit_password);
		mUserType = getIntent().getIntExtra(Constant.USER_TYPE, 1);
		close = findViewById(R.id.close, TextView.class);
		GlobalSettings.mIsLoginActivity = false;
		mBottomText = this.findViewById(R.id.text_bottom, TextView.class);
		mBottomText
				.setText(Html
						.fromHtml("使用皮肤科医生，就表示您同意皮肤科医生的<br/><u><font color=\"#FFFFFF\">使用条款</font></u>&nbsp;和&nbsp;<u><font color=\"#FFFFFF\">隐私政策</font></u>"));
		mBottomText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(getContext(), ShengmingActivity.class));
			}
		});

		String loginUserName = GlobalSettings.getLoginUserName(this);
		edit_username.setText(loginUserName);
		if (!loginUserName.isEmpty()) {
			edit_password.requestFocus();
		}

		close.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				GlobalSettings.mIsLoginActivity = true;
				onBackPressed();
				// http://a.app.qq.com/o/simple.jsp?pkgname=com.pifuke.patient
				Uri uri = Uri
						.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.pifuke.patient");
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);

			}
		});

		cache = new File(Environment.getExternalStorageDirectory(), "cache");

		if (!cache.exists()) {
			cache.mkdirs();
		}

		GlobalSettings.login_type = GlobalSettings.LOGIN_TYPE_UNKNOWN;
		
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE) {

		} else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			GlobalSettings.sUser = null;
			GlobalSettings.sToken = null;
			CommonUtility.finish();
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onResume() {
		super.onResume();

		// MobclickAgent.onResume(this);

		if (!CommonUtility.isNull(code)) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("appid", ShareWXUtils.APP_ID);
			params.put("secret", ShareWXUtils.APP_SECRET);
			params.put("code", code);
			params.put("grant_type", "authorization_code");
			RequestTaskIntercept.requestIntercept(getContext(),
					"https://api.weixin.qq.com/sns/oauth2/access_token",
					new RequestHandler(getContext(), new HandlerCallback() {

						@Override
						public void callback(Object o) {
							if (!CommonUtility.isNull(o)) {
								JSONObject object = (JSONObject) o;
								if (object.has("access_token")) {
									try {
										HashMap<String, Object> params_weixin = new HashMap<String, Object>();
										params_weixin.put(Constant.PARAM_API,
												"User.ThirdLogin");
										params_weixin.put("third_type",
												"weixin");
										params_weixin.put("third_token", object
												.getString("access_token"));
										params_weixin.put("third_id",
												object.getString("unionid"));
										params_weixin.put("appname",
												Constant.APP_NAME);

										if (access_token == null) {
											access_token = new String();
											access_token = object
													.getString("access_token");
										}

										if (weixin_Oppenid == null) {
											weixin_Oppenid = new String();
											weixin_Oppenid = object
													.getString("openid");
										}

										GlobalSettings.login_type = GlobalSettings.LOGIN_TYPE_THIRD;
										login(params_weixin);
										
										if(!GlobalSettings.getLoginFrist(LoginActivity.this)){
											new Handler().postDelayed(
													new Runnable() {

														@Override
														public void run() {
															getWeixinUserInfo();

														}
													}, 1000);
										}

										
									} catch (Exception e) {
										e.printStackTrace();
									}
								} else {
									CommonUtility.tip(getContext(), "微信授权失败");
								}
							}
						}
					}), params);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
			if (data != null) {
			}
		}

	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_login) {
			String username = edit_username.getText().toString();
			String password = edit_password.getText().toString();
			if (!CommonUtility.isNull(username)
					&& !CommonUtility.isNull(password)) {
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put(Constant.PARAM_API, "User.Login");
				params.put("mobile", username);
				params.put("pwd", OUtil.md5(password));
				params.put("appname", Constant.APP_NAME);
				GlobalSettings.login_type = GlobalSettings.LOGIN_TYPE_USERNAME;
				login(params);
			} else {
				CommonUtility.toast(getContext(), "请输入用户名和密码");
			}
		} else if (id == R.id.btn_login_by_weixin) {

			IWXAPI wxApi = WXAPIFactory.createWXAPI(getContext(),
					ShareWXUtils.APP_ID, false);

			if (isWXAppInstalledAndSupported(LoginActivity.this, wxApi)) {
				final SendAuth.Req req = new SendAuth.Req();
				req.scope = "snsapi_userinfo";
				req.state = "com.smiier.skin.LoginActivity";
				wxApi.sendReq(req);
			} else {
				Toast.makeText(LoginActivity.this, "您尚未安装微信客户端",
						Toast.LENGTH_SHORT).show();
			}
		} else if (id == R.id.btn_login_by_qq) {

			// if (CommonUtility.isDoctor()) {
			mQQAuth = QQAuth.createInstance(Constant.QQ_APP_ID, this);
			mTencent = Tencent.createInstance(Constant.QQ_APP_ID, this);
			/*
			 * } else { mQQAuth =
			 * QQAuth.createInstance(Constant.QQ_APP_ID_PATIENT, this); mTencent
			 * = Tencent.createInstance(Constant.QQ_APP_ID_PATIENT, this); }
			 */

			if (mQQAuth.isSessionValid()) {
				mQQAuth.logout(getContext());
			}

			if (!mQQAuth.isSessionValid()) {
				IUiListener listener = new BaseUiListener() {
					@Override
					protected void doComplete(JSONObject values) {
						try {
							HashMap<String, Object> params = new HashMap<String, Object>();
							params.put(Constant.PARAM_API, "User.ThirdLogin");
							params.put("third_type", "qq");
							params.put("third_token",
									values.getString("access_token"));
							params.put("third_id", values.getString("openid"));
							params.put("appname", Constant.APP_NAME);
							GlobalSettings.login_type = GlobalSettings.LOGIN_TYPE_THIRD;
							login(params);

							getQQUserInfo();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};
				// mQQAuth.login(this, "all", listener);

				mTencent.loginWithOEM(this, "all", listener, "10000144",
						"10000144", "xxxx");

				/*
				 * mTencent.loginWithOEM(this, "all", listener, "10000144",
				 * "10000144", "xxxx");
				 */

			} else {
				finish();
			}
		} else if (id == R.id.btn_login_by_sina) {
			// 创建授权认证信息
			AuthInfo authInfo = null;
			if (CommonUtility.isDoctor()) {
				authInfo = new AuthInfo(this, Constant.WEIBO_APP_KEY,
						Constant.REDIRECT_URL, Constant.SCOPE);
			} else {
				authInfo = new AuthInfo(this, Constant.WEIBO_APP_KEY_PATIENT,
						Constant.REDIRECT_URL, Constant.SCOPE);
			}

			if (authInfo != null) {
				WeiboAuth weiboAuth = new WeiboAuth(getContext(), authInfo);
				mSsoHandler = new SsoHandler((Activity) getContext(), weiboAuth);
			}
			if (mSsoHandler != null) {
				mSsoHandler.authorize(new AuthListener() {

					@Override
					public void onComplete(Bundle values) {
						final Oauth2AccessToken accessToken = Oauth2AccessToken
								.parseAccessToken(values);
						if (accessToken != null && accessToken.isSessionValid()) {
							try {
								HashMap<String, Object> params = new HashMap<String, Object>();
								params.put(Constant.PARAM_API,
										"User.ThirdLogin");
								params.put("third_type", "sina");
								params.put("third_token",
										accessToken.getToken());
								params.put("appname", Constant.APP_NAME);
								params.put("third_id", accessToken.getUid());
								GlobalSettings.login_type = GlobalSettings.LOGIN_TYPE_THIRD;
								login(params);
								
								
								
								if(!GlobalSettings.getLoginFrist(LoginActivity.this)){
									new Handler().postDelayed(new Runnable() {

										@Override
										public void run() {
											show(Long.parseLong(accessToken
													.getUid()), mListener,
													accessToken);

										}
									}, 1000);
								}

							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					@Override
					public void onWeiboException(WeiboException e) {
					}
				});
			}
		} else if (id == R.id.btn_register) {
			startActivity(new Intent(this, RegisterFirstStepActivity.class));
		} else if (id == R.id.text_forget_password) {
			Intent intent = new Intent(getContext(),
					RegisterFirstStepActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY_1,
					Constant.TYPE_FORGET_PASSWORD);
			startActivity(intent);
		}
	}

	private boolean isWXAppInstalledAndSupported(LoginActivity loginActivity,
			IWXAPI wxApi) {

		boolean sIsWXAppInstalledAndSupported = wxApi.isWXAppInstalled()
				&& wxApi.isWXAppSupportAPI();
		if (!sIsWXAppInstalledAndSupported) {

			return false;
		}

		return true;
	}

	// QQ登录回调
	private class BaseUiListener implements IUiListener {

		@Override
		public void onComplete(Object response) {
			// Util.showResultDialog(activity, response.toString(), "登录成功");
			doComplete((JSONObject) response);
		}

		protected void doComplete(JSONObject values) {
			
			
			Log.i("testqq", "values:" + values);
			
			if(!GlobalSettings.getLoginFrist(LoginActivity.this)){
				if (GlobalSettings.sUser == null) {
					GlobalSettings.sUser = new User();
				}
				
				try {

					if (values.getString("nickname") != null
							&& !values.getString("nickname").isEmpty()) {
						GlobalSettings.sUser.Name = values.getString("nickname");
					}

					int gender = 0;

					if (!values.getString("gender").equals("男")) {
						gender = 1;
					}

					GlobalSettings.sUser.Sex = gender;

					// postUserSex(GlobalSettings.sUser.Sex);

					if (values.getString("figureurl_qq_2") != null
							&& !values.getString("figureurl_qq_2").isEmpty()) {
						GlobalSettings.sUser.Pic = values.getString("figureurl");
					}

					// getImageURI(GlobalSettings.sUser.Pic, cache);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			
		}

		@Override
		public void onError(UiError e) {
			Util.dismissDialog();
		}

		@Override
		public void onCancel() {
			Util.dismissDialog();
		}
	}

	// weibo登录回调
	private class AuthListener implements WeiboAuthListener {
		@Override
		public void onComplete(Bundle values) {
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT)
					.show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getContext(), ".......", Toast.LENGTH_SHORT).show();
		}
	}

	void login(final HashMap<String, Object> params) {

		RequestTaskIntercept.requestIntercept(getContext(),
				Constant.URL.REQUEST, new RequestHandler(getContext(),
						new HandlerCallback() {

							@Override
							public void callback(Object o) {
								if (!CommonUtility.isNull(o)) {
									JSONObject object = (JSONObject) o;
									if (CommonUtility.response200(object)) {
										try {
											object = CommonUtility
													.responseRes(object);
											GlobalSettings.sToken = object
													.getString(Constant.JSON_PARAM_TOKEN);
											GlobalSettings.sUid = object
													.getInt(Constant.PARAM_UID);

											GlobalSettings.setLoginType(
													getContext(),
													GlobalSettings.login_type);
											if (GlobalSettings.login_type == GlobalSettings.LOGIN_TYPE_USERNAME) {
												GlobalSettings
														.setLoginUserName(
																getContext(),
																(String) params
																		.get("mobile"));
												GlobalSettings.setLoginUserPwd(
														getContext(),
														(String) params
																.get("pwd"));
											} else if (GlobalSettings.login_type == GlobalSettings.LOGIN_TYPE_THIRD) {
												GlobalSettings
														.setLoginThirdType(
																getContext(),
																(String) params
																		.get("third_type"));
												GlobalSettings
														.setLoginThirdId(
																getContext(),
																(String) params
																		.get("third_id"));
											}
											// 不管什么方式登陆成功都将code置为null，防止下次进入登陆页面时重复微信登陆
											code = null;
											RequestTaskIntercept
													.requestIntercept(
															getContext(),
															Constant.URL.REQUEST,
															new RequestHandler(
																	getContext(),
																	new HandlerCallback() {

																		@Override
																		public void callback(
																				Object o) {
																			if (!CommonUtility
																					.isNull(o)) {
																				try {
																					JSONObject object = (JSONObject) o;
																					JSONArray array = object
																							.getJSONArray(Constant.JSON_PARAM_RES);
																					if (array
																							.length() > 0) {
																						GlobalSettings.sUser = JsonUtil
																								.convertFromObject(
																										array.getJSONObject(0),
																										User.class);
																						GlobalSettings.sUser.User_Type = 2;

																						/**
																						 * 在此判断是否有电话号码
																						 */
																						
																						
																						Log.i("testqqmobile", "mobile.isnullL:" + (GlobalSettings.sUser.Mobile == null
																								|| GlobalSettings.sUser.Mobile
																								.isEmpty()));

																						if (GlobalSettings.sUser.Mobile == null
																								|| GlobalSettings.sUser.Mobile
																										.isEmpty()) {
																							/**
																							 * 增加验证手机的逻辑
																							 */

																							if (GlobalSettings.sUser.Name != null
																									&& !GlobalSettings.sUser.Name
																											.isEmpty()) {
																								postUserName(GlobalSettings.sUser.Name);
																							}
																							
																							GlobalSettings.setLoginFrisr(LoginActivity.this, true);

																							postUserSex(GlobalSettings.sUser.Sex);

																							if (GlobalSettings.sUser.Pic != null
																									&& !GlobalSettings.sUser.Pic
																											.isEmpty()) {
																								getImageURI(
																										GlobalSettings.sUser.Pic,
																										cache);
																							}

																							Intent intent = new Intent();
																							intent.setClass(
																									LoginActivity.this,
																									RegisterFirstStepActivity.class);
																							LoginActivity.this
																									.startActivity(intent);
																						}else{
																							
																							GlobalSettings.setLoginFrisr(LoginActivity.this, true);
																							
																							HashMap<String, Object> param = new HashMap<String, Object>();
																							param.put(
																									"token",
																									GlobalSettings.sToken);
																							param.put(
																									Constant.PARAM_API,
																									"User.Set");
																							param.put(
																									"GT_ClientID",
																									PushManager
																											.getInstance()
																											.getClientid(
																													getApplicationContext()));
																							RequestTaskIntercept
																									.requestIntercept(
																											getContext(),
																											Constant.URL.REQUEST,
																											new RequestHandler(
																													getContext(),
																													new HandlerCallback() {

																														@Override
																														public void callback(
																																Object o) {
																															JSONObject obj;
																															try {
																																obj = new JSONObject(
																																		o.toString());
																																if (o != null
																																		&& obj.getInt("ResultCode") == 200) {
																																	if (GlobalSettings.sUser.User_Type == 0) {
																																		Intent intent = new Intent(
																																				getContext(),
																																				PatientProfileEditActivity.class);
																																		intent.putExtra(
																																				Constant.IDENTITY_KEY,
																																				true);
																																		startActivity(intent);
																																	} else {
																																		
																																		Log.i("testqqmobile", "mobile.isnullTwo:" + (!GlobalSettings.getLoginFrist(LoginActivity.this)));
																																		
																																		
																																		if(GlobalSettings.sUser.Mobile != null
																																				|| !GlobalSettings.sUser.Mobile.isEmpty() ){
																																			Intent intent = new Intent(
																																					getContext(),
																																					GlobalSettings
																																							.getActivity4Navigate(LoginActivity.this));
																																			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
																																					| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
																																			startActivity(intent);
																																		}
																																		
																																	}
																																	Intent intent = new Intent(
																																			Constant.RECIVER_QUESTION);
																																	intent.putExtra(
																																			Constant.IDENTITY_KEY_USER_TYPE,
																																			1);
																																	sendBroadcast(intent);
																																}
																															} catch (JSONException e) {
																																// TODO
																																// Auto-generated
																																// catch
																																// block
																																e.printStackTrace();
																															}

																														}
																													}),
																											param);
																							
																						}
																						
																						
																						/*if(GlobalSettings.sUser.Mobile != null && !GlobalSettings.sUser.Mobile.isEmpty()){
																							GlobalSettings.setLoginFrisr(LoginActivity.this, true);
																						}*/
																						
																					
																					}
																				} catch (Exception e) {
																					e.printStackTrace();
																				}
																			}
																		}
																	}),
															CommonUtility
																	.params(new String[] {
																			Constant.PARAM_API,
																			"uids",
																			"appname" },
																			new Object[] {
																					"User.Get",
																					GlobalSettings.sUid,
																					Constant.APP_NAME }));
										} catch (Exception e) {
											e.printStackTrace();
										}
									} else {
										JSONObject obj;
										try {
											obj = new JSONObject(o.toString());
											if (obj.getInt("ResultCode") == -2004) {
												View v = LayoutInflater.from(
														activity).inflate(
														R.layout.login_alert,
														null);

												final OAlert alert = new OAlert(
														getContext());
												alert.setContentView(v);
												alert.show();
												v.findViewById(R.id.download)
														.setOnClickListener(
																new OnClickListener() {

																	@Override
																	public void onClick(
																			View v) {
																		Uri uri = Uri
																				.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.pifuke.patient");
																		Intent intent = new Intent(
																				Intent.ACTION_VIEW,
																				uri);
																		startActivity(intent);
																	}
																});
												v.findViewById(R.id.cancel)
														.setOnClickListener(
																new OnClickListener() {

																	@Override
																	public void onClick(
																			View v) {
																		alert.dismiss();
																	}
																});
											} else {
												CommonUtility.toast(
														getContext(),
														CommonUtility
																.info(object));

												Log.i("testlogin", "else");
											}

										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}

									}
								}
							}
						}), params);
	}

	/*
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

	protected void getQQUserInfo() {
		mInfo = new UserInfo(this, mTencent.getQQToken());

		if (ready(this, mTencent)) {
			mInfo.getUserInfo(new BaseUiListener() {
			});
		}
	}

	protected void getWeixinUserInfo() {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("access_token", access_token);
		params.put("openid", weixin_Oppenid);

		RequestTaskIntercept.requestIntercept(getContext(),
				"https://api.weixin.qq.com/sns/userinfo", new RequestHandler(
						getContext(), new HandlerCallback() {

							@Override
							public void callback(Object o) {
								JSONObject object;
								try {
									object = new JSONObject(o.toString());

									Log.i("testweixin", "suer:"
											+ (GlobalSettings.sUser == null));

									if (GlobalSettings.sUser == null) {
										GlobalSettings.sUser = new User();
									}

									if (object.getString("sex").equals("2")) {
										GlobalSettings.sUser.Sex = 1;
									} else {

										GlobalSettings.sUser.Sex = 0;
									}

									// postUserSex(GlobalSettings.sUser.Sex);

									if (object.getString("headimgurl") != null
											&& !object.getString("headimgurl")
													.isEmpty()) {
										GlobalSettings.sUser.Pic = object
												.getString("headimgurl");
									}

									// getImageURI(GlobalSettings.sUser.Pic,
									// cache);

									if (object.getString("nickname") != null
											&& !object.getString("nickname")
													.isEmpty()) {
										GlobalSettings.sUser.Name = object
												.getString("nickname");

										// postUserName(GlobalSettings.sUser.Name);
									}

								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
						}), params);

	}

	private RequestListener mListener = new RequestListener() {
		@Override
		public void onComplete(String response) {

			try {
				Log.i("testweibo", "response:" + (new JSONObject(response)));
			} catch (JSONException e) {
				// TODO Auto-generated catch block

				Log.i("testweibo", "response.error:" + e.toString());
				e.printStackTrace();
			}

		}

		@Override
		public void onWeiboException(WeiboException e) {

			Log.i("testweibo", "weiboException:" + e.toString());

		}
	};

	public void show(long uid, RequestListener listener,
			Oauth2AccessToken accessToken) {

		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("access_token", accessToken.getToken());
		params.put("uid", uid);
		params.put("appkey", Constant.WEIBO_APP_KEY);

		RequestTaskIntercept.requestIntercept(getContext(), sAPIList
				.get(READ_USER), new RequestHandler(getContext(),
				new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (GlobalSettings.sUser == null) {
							GlobalSettings.sUser = new User();
						}

						try {
							JSONObject object = new JSONObject(o.toString());

							int demo = 0;

							if (object.getString("gender") != null
									&& !object.getString("gender").isEmpty()) {
								if (object.getString("gender").equals("m")) {
									demo = 0;
								} else {
									demo = 1;
								}
							}

							GlobalSettings.sUser.Sex = demo;

							// postUserSex(GlobalSettings.sUser.Sex);

							if (object.getString("name") != null
									&& !object.getString("name").isEmpty()) {
								GlobalSettings.sUser.Name = object
										.getString("name");

								// postUserName(GlobalSettings.sUser.Name);

							}

							if (object.getString("avatar_hd") != null
									&& !object.getString("avatar_hd").isEmpty()) {
								GlobalSettings.sUser.Pic = object
										.getString("avatar_hd");

								// getImageURI(GlobalSettings.sUser.Pic, cache);
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}), params);
	}

	public static boolean ready(Context context, Tencent mTencent) {
		if (mTencent == null) {
			return false;
		}
		boolean ready = mTencent.isSessionValid()
				&& mTencent.getQQToken().getOpenId() != null;
		if (!ready) {
			Toast.makeText(context, "login and get openId first, please!",
					Toast.LENGTH_SHORT).show();
		}
		return ready;
	}

	private void postUserName(String name) {

		HashMap<String, Object> params = new HashMap<String, Object>();
		// params.put(param_key, value);
		params.put("Name", name);
		params.put(Constant.PARAM_API, "User.Set");
		params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							try {
								int resultCode = object
										.getInt(Constant.JSON_PARAM_RESCODE);
								if (CommonUtility.response200(object)) {
									CommonUtility.toast(activity, "姓名保存成功");
								} /*
								 * else if (resultCode == -2005) { CommonUtility
								 * .tip(activity, "您已经认证或者正在等待审核认证中，不可修改数据。"); }
								 * else { CommonUtility.tip( activity,
								 * "修改失败，请稍后再试。"); }
								 */
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), params);

	}

	private void postUserSex(int sex) {
		HashMap<String, Object> params = new HashMap<String, Object>();

		/**
		 * 男 0 女 1
		 */

		String content = sex + "";
		params.put("Sex", content);
		params.put(Constant.PARAM_API, "User.Set");
		params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							try {
								int resultCode = object
										.getInt(Constant.JSON_PARAM_RESCODE);
								if (CommonUtility.response200(object)) {
									CommonUtility.toast(activity, "性别保存成功");
								}

							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), params);
	}

	protected void uploadPic(File file) {
		File f = file;

		if (f.exists()) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			params.put("pic", f);
			params.put(Constant.PARAM_API, "SYS.UploadPic");
			RequestTaskIntercept.requestIntercept(activity,
					Constant.URL.REQUEST, new RequestHandler(activity,
							new HandlerCallback() {
								@Override
								public void callback(Object o) {
									if (!CommonUtility.isNull(o)) {
										try {
											JSONObject object = (JSONObject) o;
											if (CommonUtility
													.response200(object)) {
												final String path = object
														.getString(Constant.JSON_PARAM_RES);
												HashMap<String, Object> params_ = new HashMap<String, Object>();
												params_.put(
														Constant.PARAM_TOKEN,
														GlobalSettings.sToken);
												params_.put("Pic", path);
												params_.put(Constant.PARAM_API,
														"User.Set");
												RequestTaskIntercept
														.requestIntercept(
																activity,
																Constant.URL.REQUEST,
																new RequestHandler(
																		activity,
																		new HandlerCallback() {

																			@Override
																			public void callback(
																					Object o) {
																				if (!CommonUtility
																						.isNull(o)) {
																					JSONObject object = (JSONObject) o;
																					if (CommonUtility
																							.response200(object)) {
																						try {
																							GlobalSettings.sUser.Pic = path;
																						} catch (Exception e) {
																							e.printStackTrace();
																						}
																					}
																				}
																			}
																		}),
																params_);
											}
										} catch (Exception e) {
											e.printStackTrace();
										}
									}

								}
							}), params);
		}
	}

	public void getImageURI(final String picURL, final File cache) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				String name = "mf_pic";
				final File file = new File(cache, name);
				// 如果图片存在本地缓存目录，则不去服务器下载
				// 从网络上获取图片
				URL url;
				try {

					url = new URL(picURL);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");
					Log.i("testdown", "get:");
					conn.setDoInput(true);

					if (conn.getResponseCode() == 200) {

						InputStream is = conn.getInputStream();
						FileOutputStream fos = new FileOutputStream(file);
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = is.read(buffer)) != -1) {
							fos.write(buffer, 0, len);
						}
						is.close();
						fos.close();

						if (file.exists()) {

							LoginActivity.this.runOnUiThread(new Runnable() {

								@Override
								public void run() {
									uploadPic(file);

								}
							});

						}
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}

}
